
using System;
using System.Collections;
using System.Diagnostics;
using System.ComponentModel;

using System.IO;

using CStock;


using CUtil;




namespace CStock
{
	
	/// <summary>
	/// Summary description for Assets.
	/// </summary>
    public class Assets : StockObjectCollection, IAssets
	{
       
        #region Constructor
        public Assets(): base()
		{

            ResetPathFromConfiguration();
		}
        public override bool ResetPathFromConfiguration()
        {

            ProgramContext pc = ProgramContext.Instance;
            Debug.Assert(pc != null, "Initialize ProgramContext first ...");
            if (pc != null)
                this.path = pc.Configuration.Directories.AssetPath;
            return true;


        }
		#endregion	

		#region Class ArrayList Override

       
    


		/// <summary>
		/// 
		/// </summary>
		/// <param name="obj"></param>
		/// <returns></returns>
		public int Add(object obj)
		{
			Asset newAsset = (Asset)obj;
			
            if (this.Items.Count <= 0)
			{
                //if it is empty - add the Asset
				this.items.Add(newAsset);
				return 0;
			}
			else
			{
                //check if the Asset is already there!
				if (!this.items.Contains(newAsset))
				{
                    //No

                    //now add at a place so that we keep some order...
                    int index = this.Items.Count;
                    //for (int i = 0; i < this.Items.Count; i++)
                    //{
                    //    Asset listAsset = (Asset)this[i];
                        
                    //}
					this.Items.Insert(index,newAsset);
					//OnChanged(EventArgs.Empty);
					return index;
				}
				else
				{
                    //the Asset is already in the list!
                    Debug.Assert(false, "CAssets", "Error adding Asset - alread in the list " + newAsset.Name);
					return -1;
				}
			}
		}
     

		public int IndexOf(object obj)
		{
			return this.items.IndexOf(obj);
		}
		#endregion



		#region Implementation
		
		/// <summary>
		/// 
		/// </summary>
		public new IAsset this[string name]
		{
			get
			{
				for(int i = 0; i < this.items.Count; i ++)
				{
                    StockObjectBase myPf = this[i] as StockObjectBase;
					if( myPf.ID == name)
						return myPf as IAsset;
				}
				return null;
			}
		}
       
		public new IAsset this[int index]
		{
			get
			{
				try
				{
					if ((index >= 0) && (index < this.items.Count))
					{
						object o = base[index];
						return o as IAsset;
					}
					else
					{
						return null;
					}
				}
				catch
				{
					Debug.Assert(false,"Asset : Error getting Asset");
					return null;
				}
			}
			set
			{
				if ((index >= 0) && (index < this.items.Count))
				{
					base[index] = value;
				}
			}
		}
	

		#endregion


        /// <summary>
        /// name convention for Assets: Contain the Trader name!!! Economy_Asset1
        /// </summary>
        /// <returns></returns>
        public override bool Serialize()
        {
            this.ResetPathFromConfiguration();

            for(int i = 0; i < this.items.Count; i++)
            {
                StockObjectBase myPf = this[i] as StockObjectBase;
                myPf.ResetPathFromConfiguration();
                myPf.Serialize();
            }
            return true;

        }
        /// <summary>
        /// name convention for Assets: Contain the Trader name!!! Economy_Asset1
        /// </summary>
        /// <returns></returns>
        public override object DeSerialize()
        {
            if(this.items.Count > 0)
                this.items.RemoveRange(0, this.items.Count -1);

           
            //Check ID!
            Debug.Assert(!String.IsNullOrEmpty(this.iD));
            

            ProgramContext dh = ProgramContext.Instance;
            string path = dh.Configuration.Directories.AssetPath;

            //search for all Assets:
            
            //-------------------------------------------
            //search for files in that dir
            System.IO.DirectoryInfo di = new DirectoryInfo(path);
            if (!System.IO.Directory.Exists(path))
                System.IO.Directory.CreateDirectory(path);

            dh.Logfile.WriteTimeSpanLog("   Reading asset Directory: " + path);

            foreach (FileInfo file in di.GetFiles("*.xml"))
            {

                string strFile = file.Name;
                string idAsset = CUtil.IOUtil.ExtractNameFromFileName(strFile);
                string id = CUtil.IOUtil.ExtractBetween_(idAsset, 0);
                


                if (!String.IsNullOrEmpty(id))
                {
                    StockObjectBase portf = new Asset();
                    portf.ID = idAsset;

                    object o = new Asset();
                    
                    if (portf.DeSerialize(ref o))
                    {
                        portf = o as Asset;
                        this.Add(portf);
                        dh.Logfile.WriteTimeSpanLog("       -success deserializing Asset: " + idAsset);
                    }
                }

            }

         
            
            return new object();

        }
      
  
        /// <summary>
        /// ToAssetItemArray
        /// </summary>
        /// <returns></returns>
        public Asset[] ToAssetItemArray()
		{
			try
			{
                return (Asset[])this.items.ToArray(typeof(Asset));
			}
			catch (Exception exc)
			{
				Debug.WriteLine("DataItems - Error creating AssetItemArray" + exc.Message);
			}
			return null;
		}
      
	}
}
